const randomId = () => {
  // RFC4122 version 4 compliant UUID
  const id = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
    const r = (Math.random() * 16) | 0;
    const v = c === "x" ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
  return `alert-${id}`;
};

const closeNode = `
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
`;

const loader = `
  <div class="ball-clip-rotate d-flex">
    <div></div>
  </div>
`;

const loaderWithStr = (str) => {
  return `
    <div>
      <div class="ball-clip-rotate d-flex justify-content-center mb-3">
        <div></div>
      </div>
      <p class="text-muted font-weight-light">${str}</p>
    </div>
  `;
};

// alert
// --------------------

export const hideAlerts = () => {
  $(".alert").alert('close');
};

export const alert = ({
  // [primary,secondary,success,danger,warning,info,light,dark]
  type = "primary",
  classes,
  target = document.body,
  close = true,
  stay = true,
  time = 3000,
  content,
  linkId,
  linkCallback,
  hideLink = false
}) => {
  const element = $(`<div class="alert" role="alert"></div>`);
  const classNames = `alert-${type} ${classes}`;
  const id = randomId();

  element.attr("id", id);
  element.addClass(classNames);
  element.html(close ? content + closeNode : content);
  element.prependTo($(target));

  if (!stay) {
    setTimeout(function() {
      $(`#${id}`).alert('close');
    }, time);
  }

  if (linkId) {
    $(linkId).click(function(event) {
      if (linkCallback) {
        event.preventDefault();
        linkCallback();
        if (hideLink) {
          $(this).remove();
        }
      }
    });
  }
};

// msg
// --------------------

export const msg = ({
  target = document.body,
  content,
  time = 3000,
}) => {
  const element = $(`<div class="msg"></div>`);
  const id = randomId();

  element.attr("id", id);
  element.html(content);
  element.appendTo($(target));

  if (time) {
    setTimeout(function() {
      $(`#${id}`).remove();
    }, time);
  }
};

// loading
// --------------------

export const hideLoading = () => {
  $('.loader-full').remove();
};

export const loading = ({
  target = document.body,
  content,
  fixed = false,
  time = 3000
}) => {
  const element = $(`<div class="loader-full ${fixed ? "position-fixed" : ""}"></div>`);
  const id = randomId();

  element.attr("id", id);
  element.html(content ? loaderWithStr(content) : loader);
  element.prependTo($(target));

  if (time) {
    setTimeout(function() {
      $(`#${id}`).remove();
    }, time);
  }
};

// --------------------
// exports
// --------------------

export default {
  hideAlerts,
  alert,
  msg,
  hideLoading,
  loading
};
